#include <stdio.h>

#include <pthread.h>
static int number = 0;
// 初始化互斥锁
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 初始化条件变量
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *do_thread(void *arg)
{
    // 子线程进行生产参数是几就生产多少个
    int i;
    int cnt = atoi((char *)arg);
    for (i = 0; i < cnt; i++)
    {
        // 生产者生产数据
        pthread_mutex_lock(&mutex);

        printf("生产者生产数据，当前数据为：%d\n", ++number);
        pthread_mutex_unlock(&mutex);
        // 生产者生产数据后，通知消费者消费数据
        pthread_cond_signal(&cond);
    }
    pthread_exit((void *)0);
}
int main(int argc, char const *argv[])
{

    // 创建线程
    pthread_t tid;
    int i;
    int total_of_product = 0;
    int total_of_consume = 0;
    bool is_exit = false;
    for (i = 1; i < argc; i++)
    {
        total_of_product += atoi(argv[i]);
        pthread_create(&tid, NULL, do_thread, (void *)argv[i]);
    }

    while (1)
    {
        pthread_mutex_lock(&mutex);
        // 主线程消费
        while (number == 0)
        {
            pthread_cond_wait(&cond, &mutex); // 当生产后这里会被唤醒
        }
        while (number > 0)
        {
            total_of_consume++;
            printf("消费者消费数据，当前数据为：%d\n", number--);
            is_exit = total_of_consume >= total_of_product;
        }
        pthread_mutex_unlock(&mutex);
        if (is_exit)
        {
            break;
        }
    }

    return 0;
}
